/*
 * @lc app=leetcode.cn id=725 lang=typescript
 *
 * [725] 分隔链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function splitListToParts(head: ListNode | null, k: number): Array<ListNode | null> {
  // 特判
  if (head === null) return new Array(k).fill(null);

  let n = 0;
  // 链表指针，当前指向的位置
  let p: ListNode | null = head;
  // 计算链表长度
  while (p !== null) {
    p = p.next;
    n++;
  }

  let avg = (n / k) >> 0;
  let mod = n % k;

  // 返回分割后的链表头，并重置p指针位置为下一组第一个节点
  const countLink = (k: number): ListNode | null => {
    if (p === null) return null;
    let head = p;
    let q = p;
    while (q && --k) {
      q = q.next;
    }

    if (q) {
      p = q.next;
      q.next = null;
    }
    return head;
  };
  let ans: Array<ListNode | null> = [];
  p = head;
  // 分隔链表
  for (let i = 0; i < k; i++) {
    let tmp = avg;
    if (mod > 0) {
      tmp++;
      mod--;
    }
    const res = countLink(tmp);
    ans.push(res);
  }

  return ans;
}
// @lc code=end
